<?php

namespace App\Http\Controllers\Home;

use App\Models\Address;
use App\Models\BucketLog;
use App\Models\Member;
use App\Models\MemberCash;
use App\Models\MemberCommission;
use App\Models\MemberCommissionLog;
use App\Models\MemberScore;
use App\Models\MemberScoreLog;
use App\Models\MemberWaterBill;
use App\Models\MemberWaterBillLog;
use App\Models\Order;
use App\Models\Picture;
use App\Models\ReferCode;
use App\Models\Shop;
use App\Models\SmsLog;
use App\Models\WaterBillOrder;
use App\Models\WechatSet;
use App\Support\Printer;
use App\Models\WxTpl;
use App\Models\MemberWithdraw;
use App\Support\WechatSilentAuth;
use Carbon\Carbon;

/**
 * 订单控制器
 */
class MemberController extends BaseController
{

    public function __construct(
        Member $member,
        Address $address,
        Order $order,
        MemberWaterBillLog $memberWaterBillLog,
        MemberWaterBill $memberWaterBill,
        Picture $picture,
        MemberCash $memberCash,
        SmsLog $smsLog,
        Shop $shop,
        BucketLog $bucketLog,
        WaterBillOrder $waterBillOrder,
        WxTpl $wxTpl,
        MemberWithdraw $memberWithdraw,
        MemberCommissionLog $commissionLog,
        WechatSet $wechatSet,
        MemberCommission $commission,
        ReferCode $referCode,
        MemberScore $memberScore,
        MemberScoreLog $scoreLog
    )
    {
        parent::__construct();
        $this->member = $member;
        $this->address = $address;
        $this->order = $order;
        $this->memberWaterBillLog = $memberWaterBillLog;
        $this->memberWaterBill = $memberWaterBill;
        $this->picture = $picture;
        $this->memberCash = $memberCash;
        $this->smsLog = $smsLog;
        $this->shop = $shop;
        $this->bucketLog = $bucketLog;
        $this->waterBillOrder = $waterBillOrder;
        $this->wxTpl = $wxTpl;
        $this->memberWithdraw = $memberWithdraw;
        $this->commissionLog = $commissionLog;
        $this->commission = $commission;
        $this->wechatSet = $wechatSet;
        $this->referCode = $referCode;
        $this->memberScore = $memberScore;
        $this->scoreLog = $scoreLog;
    }

    public function getIndex()
    {
//        $phone = 13027186760;
//        $logType = 1;
//        $uid = 1;
//        $res = $this->smsLog->sendCaptcha($phone, $logType, $uid);
//        dd($res);
//        $this->redis->hmset('wechat:1',['a'=>'aaa','b'=>'bbb']);
//        dump($this->redis->hmget('shop',1));
//        dump($this->redis->hgetall('shop'));
//        $this->redis->hdel('shop',1);
//        dd(unserialize(''));
    }

    public function postAddInformation()
    {
        $data['id'] = $this->mid;
        if (!$data['id']) {
            return error('非法操作');
        }
//        $data['name'] = trim(request('name'));
//        if (!$data['name']) {
//            return error('请填写姓名');
//        }
//        $data['type'] = intval(request('type'));
//        $data['company_name'] = trim(request('company_name'));
        $data['mobile'] = trim(request('mobile'));
        $old_mobile = trim(request('old_mobile'));
        if (!$data['mobile']) {
            return error('请填写手机号');
        }
        if (!is_mobile($data['mobile'])) {
            return error('请填写正确手机号');
        }
        if ($old_mobile != $data['mobile'] || request('captcha')) {
            $captcha = request('captcha');
            if (!$captcha) {
                return error('请填写验证码');
            }
            $res = $this->smsLog->checkSmsCaptcha($data['mobile'], $captcha, 2);
            if (!$res['status']) {
                return error($res['msg']);
            }
        }
        $res = $this->member->_save($data);
        if (!$res) {
            return error('操作失败');
        }
        return success('保存成功');
    }

    public function getBillRecord()
    {
        $ajaxData['record_list'] = $this->memberWaterBillLog->_getPageList(['mid' => $this->mid], '*', ['id' => 'desc']);
        return success($ajaxData);
    }

    public function getInfo()
    {
        $res = $this->member->_getOneById($this->mid);
        if (!$res) {
            return error();
        }
        $res = $res->toArray();
        $arr = explode(' ', $res['area_info']);
        $shop = $this->shop->_redisGetOneBySid($this->shop_id);
        $scoreInfo = $this->memberScore->_getOne(['mid' => $this->mid]);
        $score = $scoreInfo ? $scoreInfo['score'] : 0;
        $buy_min = $res['buy_min'] ? $res['buy_min'] : $shop['buy_min'];
        $buy_max = $res['buy_max'] ? $res['buy_max'] : $shop['buy_max'];
        $withdraw_min = isset($shop['withdraw_min']) ? $shop['withdraw_min'] : 0;
        $ajax['info'] = [
            'mid' => $res['id'],
            'aid' => $res['admin_id'],
            'sid' => $res['shop_id'],
            'avatarurl' => $res['avatarurl'],
            'shop_id' => $res['shop_id'],
            'admin_id' => $res['admin_id'],
            'shop_name' => $shop['shop_name'],
            'nickname' => $res['nickname'],
            'xcx_openid' => $res['xcx_openid'],
            'wx_openid' => $res['wx_openid'],
            'name' => $res['name'],
            'type' => $res['type'],
            'mobile' => $res['mobile'],
            'company_name' => $res['company_name'],
            'province' => isset($arr[0]) ? $arr[0] : '',
            'city' => isset($arr[1]) ? $arr[1] : '',
            'area' => isset($arr[2]) ? $arr[2] : '',
            'address' => $res['address'],
            'province_id' => $res['province_id'],
            'city_id' => $res['city_id'],
            'area_id' => $res['area_id'],
            'total_waterbill_num' => $res['total_waterbill_num'],
            'initial_bucket_num' => $res['initial_bucket_num'],
            'self_bucket_num' => $res['self_bucket_num'],
            'cash_bucket_num' => $res['cash_bucket_num'],
            'borrow_bucket_num' => $res['borrow_bucket_num'],
            'total_bucket_num' => $res['initial_bucket_num'] + $res['total_bucket_num'] - $res['total_back_bucket_num'],
            'deposit' => intval($res['deposit']),
            'buy_min' => $buy_min ? $buy_min : 1, // 最少为1
            'buy_max' => $buy_max ? $buy_max : 0, // 等于0无限制
            'withdraw_min' => $withdraw_min ? $withdraw_min : 1,
            'score' => $score,
            'refer_type' => $res['refer_type'],
            'created_at' => $res['created_at']
        ];
        return success($ajax);
    }

    public function getBuyLimit()
    {
        $res = $this->member->_getOneById($this->mid);
        if (!$res) {
            return error();
        }
        $shop = $this->shop->_redisGetOneBySid($this->shop_id);
        $buy_min = $res['buy_min'] ? $res['buy_min'] : $shop['buy_min'];
        $buy_max = $res['buy_max'] ? $res['buy_max'] : $shop['buy_max'];
        $ajax['buy_info'] = [
            'buy_min' => $buy_min ? $buy_min : 1, // 最少为1
            'buy_max' => $buy_max ? $buy_max : 0, // 等于0无限制
        ];
        return success($ajax);
    }

    public function getBillList()
    {
        $ajax['bill_list'] = $this->memberWaterBill->_redisGetBillListByMid($this->mid);
        if (!empty($ajax['bill_list'])) {
            foreach ($ajax['bill_list'] as &$v) {
                $v['goods_img'] = url('/') . $this->picture->config['savePath'] . $v['admin_id'] . '/' . $v['goods_id'] . '_1.' . $this->picture->config['saveExt'];
            }
        }
        return success($ajax);
    }

    public function getBucketRecord()
    {
        $ajaxData['record_list'] = $this->bucketLog->_getPageList(['buyer_id' => $this->mid], 'bucket_num,send_num,description,created_at', ['id' => 'desc'],8);
        return success($ajaxData);
    }

    public function getDeposit()
    {
        $ajax['info'] = $this->memberCash->_getOne(['mid' => $this->mid], 'cash as bucket_cash,cash_bucket,water_dispenser,water_dispenser_cash');
        return success($ajax);
    }

    public function postMove()
    {
        $res = $this->member->move();
        if (!$res) {
            return error($this->member->getError() ? $this->member->getError() : '未知错误');
        }
        return success('操作成功');
    }

    public function getCaptcha()
    {
        $info = $this->member->_getOneById($this->mid);
        if (!$info['mobile']) {
            return error('移交前请先完善账户资料');
        }
        $res = $this->smsLog->getSmsCaptcha($info['mobile'], 1, $this->mid);
        return $this->ajaxReturn($res);
    }

    public function getSmsCaptcha()
    {
        $mobile = trim(request('mobile'));
        if (!$mobile) {
            return error('请填写手机号');
        }
        if (!is_mobile($mobile)) {
            return error('请填写正确手机号');
        }
        $res = $this->smsLog->getSmsCaptcha($mobile, 2, $this->mid);
        return $this->ajaxReturn($res);
    }

    public function getShopList()
    {
        if($this->wx_openid){
            $where['wx_openid'] = $this->wx_openid;
        } else {
            $where['xcx_openid'] = $this->xcx_openid;
        }
        $res = $this->member->_getList($where, 'shop_id,is_default')->toArray();
        if (!$res) {
            return error('非法操作');
        }
        $key = 0;
        foreach ($res as $v) {
            if ($v['is_default']) {
                $key = $v['shop_id'];
            }
        }
        $ids = array_column($res, 'shop_id');
        $shopWhere['id'] = ['in', $ids];
        $ajaxData['shop_list'] = [];
        $shop_list = $this->shop->_getList($shopWhere, 'id,shop_name,area_info,address', ['id' => 'asc'])->toArray();
        $logopath = '/uploads/logos/imgs/' . $this->admin_id;
        if (!empty($shop_list)) {
            foreach ($shop_list as $k => $v) {
                $ajaxData['shop_list'][$k] = [
                    'id' => $v['id'],
                    'is_default' => $v['id'] == $key ? 1 : 0,
                    'shop_name' => $v['shop_name'],
                    'shop_logo' => url('/') . $logopath . '/' . $v['id'] . '_' . 1 . '.' . $this->picture->config['saveExt'] . '?time=' . time(),
                    'area_info' => $v['area_info'],
                    'address' => $v['address']
                ];
            }
        }
        $ajaxData['shop_list'] = my_sort($ajaxData['shop_list'], 'is_default', SORT_DESC);
        return success($ajaxData);
    }

    public function postChangeShop()
    {
        $new_shop_id = request('new_sid');
        if (!$new_shop_id) {
            return error('非法操作');
        }
        if($this->wx_openid){
            $where['wx_openid'] = $this->wx_openid;
        } else {
            $where['xcx_openid'] = $this->xcx_openid;
        }
        $where['shop_id'] = $new_shop_id;
        $this->member->_start();
        try {
            $this->member->_update($where, ['is_default' => 1]);
            $condition['shop_id'] = ['<>', $new_shop_id];
            if($this->wx_openid){
                $condition['wx_openid'] = $this->wx_openid;
            } else {
                $condition['xcx_openid'] = $this->xcx_openid;
            }
            $this->member->_update($condition, ['is_default' => 0]);
            $this->member->_commit();
            return success([], '切换成功');
        } catch (\Exception $e) {
            $this->member->_rollBack();
            return error('切换失败');
        }
    }

    public function getQrLink()
    {
        $type = request('type', 0); //是否生成新的二维码key
        $mid = $this->mid;
        $member = $this->member->_getOneById($mid);
        if (!$member) {
            return error();
        }
        $time = date('Y-m-d H:i:s');
        if($type) {
            $qr_key = md5($mid.$this->xcx_openid.time());
            $saveData = [
                'id' => $mid,
                'qr_key' => $qr_key,
                'qr_time' => $time
            ];
            $res = $this->member->_save($saveData);
            if(!$res) {
                return error('操作失败');
            }
        } else {
            $qr_key = $member['qr_key'];
            $qr_time = $member['qr_time'];
            if($qr_time) {
                $time = $qr_time;
            }
            if(!$qr_key) {
                return error();
            }
        }

        $result = [
            'url'   => url('/client/share-ticket.html?qrKey='.$qr_key.'&qrTime='.$time),
        ];
        return success($result);
    }

    public function getBillInfo()
    {
        $ajaxData['waterbill_list'] = $this->memberWaterBill->_redisGetBillListByMid($this->mid);
        if (isset($ajaxData['waterbill_list']) && !empty($ajaxData['waterbill_list'])) {
            foreach ($ajaxData['waterbill_list'] as $k => $v) {
                $ajaxData['waterbill_list'][$k]['goods_img'] = url('/') . $this->picture->config['savePath'] . $this->admin_id . '/' . $v['goods_id'] . '_1.' . $this->picture->config['saveExt'] . '?time=' . time();
            }
        }
        return success($ajaxData);
    }

    public function getAddressList()
    {
        $where['mid'] = $this->mid;
        $ajaxData = [];
        if ($where['mid']) {
            $ajaxData['address_list'] = $this->address->_getList($where)->toArray();
        }
        return success($ajaxData);
    }

    public function postBillAdd()
    {
        $shop = $this->shop->_redisGetOneBySid($this->shop_id);
        $msg = '';
        if ($shop['status'] != 1) {
            $msg = '系统维护升级中，暂时无法下单';
        }
        if ($msg) {
            return error($msg);
        }

        /** 正在派送，已付款-未派送，线下 */
        $where['admin_id'] = $this->admin_id;
        $where['buyer_id'] = $this->mid;
        $where['created_at'] = ['>', date('Y-m-d 00:00:00',time() -1)];
        $flag = $this->order->checkShareOrder($where, request('buyer_address'));

        if(!$flag) {
            return error('您有未完成的订单，勿重复下单');
        }
        $memberInfo = $this->member->_redisGetOneByXcxOpenId($this->xcx_openid, $this->shop_id);
        if (!$memberInfo) {
            return error('非法操作');
        }
        if (!$memberInfo['status']) {
            return error('您已被禁用，无法购买，请联系商家');
        }
        $orderData = $this->order->addBillOrder();
        if (!$orderData) {
            return error($this->order->getError() ? $this->order->getError() : 'undefined error');
        }
        set_time_limit(0);
        ob_end_clean();
        header("Connection: close");
        header("HTTP/1.1 200 OK");
        header("Content-Type: application/json;charset=utf-8");// 如果前端要的是json则添加，默认是返回的html/text
        ob_start();
        echo json_encode(['status' => 1, 'data' => [], 'msg' => '下单成功']);// 输出结果到前端
        $size = ob_get_length();
        header("Content-Length: $size");
        ob_end_flush();
        flush();
        if (function_exists("fastcgi_finish_request")) { // yii或yaf默认不会立即输出，加上此句即可（前提是用的fpm）
            fastcgi_finish_request(); // 响应完成, 立即返回到前端,关闭连接
        }
        ignore_user_abort(true);// 在关闭连接后，继续运行php脚本
        set_time_limit(0);
        $this->wxTpl->newOrderMsg($orderData, $this->shop_id);
        // 打印订单
        (new Printer())->typeSetting($orderData);
        exit;
    }

    // 用户提现账户信息
    public function getMemberCommission()
    {
        $commissionInfo = $this->commission->_getOne(['mid' => $this->mid]);
        $ajaxData = [];
        if($commissionInfo) {
            $ajaxData['info'] = $commissionInfo->toArray();
        }
        return success($ajaxData);
    }

    // 提交提现申请
    public function postApplyCommission()
    {
        $res = $this->memberWithdraw->addData();
        if(!$res) {
            $error = $this->memberWithdraw->getError();
            return error($error ? $error : '未知错误');
        }
        return success();
    }

    // 我的团队
    public function getReferTeam()
    {
        $mid = request('mid');
        $ajaxData['list'] = $this->member->_getPageList(['refer_mid' => $mid],'nickname,avatarurl,created_at',['id' => 'desc']);
        return success($ajaxData);
    }

    // 用户提现明细
    public function getWithdrawList()
    {
        $mid = request('mid');
        $statusDesc = [
            1 => '待审核',
            2 => '已审核',
            3 => '已完成',
            4 => '已驳回'
        ];
        $list = $this->memberWithdraw->_getPageList(['mid' => $mid], '*',['id' => 'desc']);
        $list['data'] = collect($list['data'])->map(function ($item)use($statusDesc) {
            $item['created_at'] = Carbon::parse($item['created_at'])->toDateString();
            $item['status_desc'] = $statusDesc[$item['status']];
            return $item;
        })->toArray();
        $ajaxData['list'] = $list;
        return success($ajaxData);
    }

    // 用户佣金明细
    public function getCommissionList()
    {
        $mid = request('mid');
        $ajaxData['list'] = $this->commissionLog->_getPageList(['mid' => $mid],'*', ['id' => 'desc']);
        return success($ajaxData);
    }

    // 用户积分明细
    public function getScoreLog()
    {
        $ajaxData['list'] = $this->scoreLog->getMemberScoreLogList($this->mid);
        return success($ajaxData);
    }

    // 积分兑换
    public function getScoreUse()
    {
        $mid = $this->mid;
        $score = request('score');
        $type = 2;
        $desc = '积分兑换';

        $res = $this->memberScore->changeMemberScore($mid, $score, $type, $desc);
        if(!$res) {
            return error('兑换失败');
        }
        return success('兑换成功');
    }

}
